﻿namespace IBTrader.Indicator
{
    using IBTrader.Charts;
    using IBTrader.Model;
    using IBTrader.Modules.Read;
    using System;
    using System.Linq;
    using System.Reflection;

    class IndicatorSwitch : IIndicator
    {
        public event EventHandler<Line> Hit;
        private readonly Store store;
        private readonly Worker worker;
        private IIndicator indicator;
        private readonly int algoId;
        private Algo algo;
        public IndicatorSwitch(Store store, Worker worker, int algoId)
        {
            this.store = store;
            this.worker = worker;
            this.algoId = algoId;
        }
        public void Init(object _1, EventArgs __)
        {
            algo = store.Algos.SingleOrDefault(a => a.Id == algoId);
            if (algo == null) return;
            algo.PropertyChanged += (_2, e) => { if (e.PropertyName == "Indicator" || e.PropertyName == "IndicatorInterval") Switch(); };
            Switch();
        }
        private void Switch()
        {
            if (indicator != null)
                indicator.Hit -= Hit;
            if (algo.Indicator != null)
                indicator = Activator.CreateInstance(Type.GetType(algo.Indicator), BindingFlags.OptionalParamBinding, null, new object[] { worker, algo.IndicatorInterval }, null) as IIndicator;
            if (indicator != null)
                indicator.Hit += Hit;
        }
        public void Add(object sender, Line line)
        {
            if (indicator != null) indicator.Add(sender, line);
        }
    }
}
